//
// Copyright (c) 2014, 保留所有权利。
//
// ContractSync.java
//
// 作    者：王红燕
// 当前版本：1.0
// 2014 下午1:16:13
//
// 
//
package com.vanke.agent.sync;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


import org.apache.log4j.Logger;

import com.vanke.agent.ADataSource;
import com.vanke.agent.C;
import com.vanke.agent.Cfg;
import com.vanke.agent.common.CstUtil;

/**
 *
 */
public class SaleServicetSync extends AgentSync {
	Logger log = Logger.getLogger(SaleServicetSync.class);

	@Override
	public void sync() {
		Set<Long> uidSet = new HashSet<Long>();
		String timeStr = dateFormat.format(saleServiceCfg.beginTime);
		saleServiceCfg.beginTime = new Date(System.currentTimeMillis());

		log.info("=============sync new SaleService===========");
		String table = "s_SaleService";
		String fields = C.FIELDS_SALESERVICE;
		Connection con = ADataSource.getConnection(ADataSource.SCHEMA_MY);
		Connection wcon = ADataSource.getConnection(ADataSource.SCHEMA_BIZ);

		try {
			String querySql = "SELECT " + fields + "  FROM " + table;
			querySql += " where CreatedOn > ? AND CreatedOn < ? ";
			log.info("execute: " + querySql + "[" + timeStr + "]");

			int columns = fields.split(",").length;

			PreparedStatement pstmt = con.prepareStatement(querySql);
			pstmt.setString(1, timeStr);
			pstmt.setString(2, dateFormat.format(saleServiceCfg.beginTime));

			ResultSet rs = pstmt.executeQuery();
			int count = 0;
			if (!rs.next()) {
				log.info("no SaleService is created");
				ADataSource.close(rs);
				ADataSource.close(pstmt);
				// 保存配置，最后一次的时间
				Cfg.set(saleServiceCfg.cfgKey,
						dateFormat.format(saleServiceCfg.beginTime));
				Cfg.save();
				return;
			}

			PreparedStatement contractPstmt = con
					.prepareStatement("select TradeGUID from s_Contract where ContractGUID = ?");
			PreparedStatement trade2CstPstmt = con
					.prepareStatement("select CstGUID from s_Trade2Cst where TradeGUID = ?");

			do {
				// 取TradeGUID
				String contractGUID = rs.getString("ContractGUID");
				contractPstmt.setString(1, contractGUID);
				ResultSet contRs = contractPstmt.executeQuery();

				String tradeGUID = null;
				while (contRs.next()) {
					tradeGUID = contRs.getString("TradeGUID");
				}
				ADataSource.close(contRs);

				// 没取到，无法关联，不做其它处理
				if (tradeGUID == null) {
					log.warn("no tradeGuid found for " + contractGUID);
					continue;
				}

				String oriGuid = null;
				trade2CstPstmt.setString(1, tradeGUID);
				ResultSet tradeRs = trade2CstPstmt.executeQuery();
				while (tradeRs.next()) {
					oriGuid = tradeRs.getString("CstGUID");
				}
				ADataSource.close(tradeRs);

				long uid = 0;

				if (oriGuid != null) {
					uid = CstUtil.getCstGUIDByOriGuid(wcon, oriGuid);
				}

				if (uid == 0) {
					uid = CstUtil.retrieveMemship(oriGuid);
				}

				if (uid == 0) {
					log.warn("no customer found in datacenter for:" + oriGuid);
					continue;
				}

				String saleTable = CstUtil.retrieveSaleServiceTable(uid);
				String insertSql = CstUtil.formatInsertSql(saleTable, fields
						+ ",CstGUID");
				PreparedStatement wpstmt = wcon.prepareStatement(insertSql);

				for (int i = 1; i <= columns; i++) {
					wpstmt.setString(i, rs.getString(i));
				}
				wpstmt.setLong(columns + 1, uid);
				try {
					wpstmt.executeUpdate();
					count++;

					Map<String, String> map = new HashMap<String, String>();
					map.put("CstGUID", String.valueOf(uid));
					String[] property = fields.split(",");
					if (property != null && property.length > 0) {
						int index = 1;
						for (String key : property) {
							map.put(key, rs.getString(index++));
						}
					}
					map.put("TradeGUID", tradeGUID);
					syncTrade2Cst(map, rs.getTimestamp("CreatedOn"), 0,uidSet);
				} catch (Exception e) {
					e.printStackTrace();
					log.error(e);
				} finally {
					ADataSource.close(wpstmt);
				}
			} while (rs.next());
			ADataSource.close(contractPstmt);
			ADataSource.close(trade2CstPstmt);

			// 保存配置，最后一次的时间
			Cfg.set(saleServiceCfg.cfgKey,
					dateFormat.format(saleServiceCfg.beginTime));
			Cfg.save();

			// 关闭
			ADataSource.close(rs);
			ADataSource.close(pstmt);

			log.info(count + " SaleService synced");
			log.info("=============sync new SaleService end===========");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(con);
			ADataSource.close(wcon);
		}
	} // ~sync

	void syncTrade2Cst(Map<String, String> recordMap, Timestamp time,
			float total,Set<Long> uidSet) {
		Connection rcon = ADataSource.getConnection(ADataSource.SCHEMA_MY);
		Connection wcon = ADataSource.getConnection(ADataSource.SCHEMA_BIZ);

		String fields = C.FIELDS_TRADE2CST;
		try {
			String sql = "select " + fields
					+ " from s_Trade2Cst  where TradeGUID=?";
			PreparedStatement rpstmt = rcon.prepareStatement(sql);
			rpstmt.setString(1, recordMap.get("TradeGUID"));
			ResultSet rs = rpstmt.executeQuery();

			String insertSql = CstUtil.formatInsertSql("s_Trade2Cst", fields);
			PreparedStatement wpstmt = wcon.prepareStatement(insertSql);
			int columns = fields.split(",").length;
			while (rs.next()) {
				try {
					for (int i = 1; i <= columns; i++) {
						wpstmt.setString(i, rs.getString(i));
					}
					wpstmt.executeUpdate();
				} catch (Exception e) {
					log.error("save trade2cst for "
							+ recordMap.get("TradeGUID") + " error:" + e);
				}
//				String content = recordMap.get("ServiceItem");
//				content = content == null ? "" : content.trim();
//				
//				String oriCstGUID = rs.getString("CstGUID");
//				long uid = CstUtil.getCstGUIDByOriGuid(wcon, oriCstGUID);
//				if (uid == 0) {
//					uid = CstUtil.retrieveMemship(oriCstGUID);
//				}
//				if (uid == 0) {
//					log.warn("no customer found in datacenter for:"
//							+ oriCstGUID);
//					continue;
//				}
//				
//				if(uidSet.contains(uid)){
//					log.warn("duplicate [ "+uid+" ] CstGUID has been found in datacenter for:"
//							+ oriCstGUID);
//					continue;
//				}else{
//					uidSet.add(uid);
//				}
//
//				JSONObject json = new JSONObject();
//				json.put("cstGUID", uid);
//
//				String projGUID = recordMap.get("ProjGUID");
//				String projCode = projCodeMap.get(projGUID);
//				if (projCode == null) {
//					projCode = CstUtil.getProjectCode(rcon, projGUID);
//					projCodeMap.put(projGUID, projCode);
//				}
//
//				json.put("projCode", projCode);
//				json.put("followTime", time == null ? 0 : time.getTime() / 1000);
//				json.put("followType", 7);
//				json.put("followContent", recordMap.get("ServiceItem"));
//				json.put("mny", total);
//
//				try {
//					QueueMapMessage ms = new QueueMapMessage();
//					ms.setMessageType(Cfg.get("jms.saleservice"));
//					ms.setObj(json.toString());
//					ms.send();
//				} catch (Exception e) {
//					log.error("send sale service notice error:" + e);
//				}
			} // end while (rs.next())

			ADataSource.close(rs);
			ADataSource.close(rpstmt);
			ADataSource.close(wpstmt);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(rcon);
			ADataSource.close(wcon);
		}
	} //~
}
